package com.cn.kabalifeuser.utils;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;

import com.cn.kabalifeuser.R;
import com.luck.picture.lib.tools.ToastUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;


@SuppressLint("SimpleDateFormat")
public class StringUtil {

    private final static String HEX = "0123456789ABCDEF";

    public static boolean isPassword(String password) {
        String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,12}";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(password);
        boolean isMatch = m.matches();
        LoggerUtils.e("是否密码正则匹配" + isMatch);
        return isMatch;
    }

    //URL地址表达式
    private final static Pattern url_pattern = Pattern.compile("(https?://(w{3}\\.)?)?\\w+\\.\\w+(\\.[a-zA-Z]+)*(:\\d{1,5})?(/\\w*)*(\\??(.+=.*)?(&.+=.*)?)?");

    public static boolean checkBankCard(String cardId) {
        if (TextUtils.isEmpty(cardId)) {
            return false;
        }
        char bit = getBankCardCheckCode(cardId
                .substring(0, cardId.length() - 1));
        if (bit == 'N') {
            return false;
        }
        return cardId.charAt(cardId.length() - 1) == bit;
    }

    /**
     * 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位
     *
     * @param nonCheckCodeCardId
     * @return
     */
    public static char getBankCardCheckCode(String nonCheckCodeCardId) {
        if (nonCheckCodeCardId == null
                || nonCheckCodeCardId.trim().length() == 0
                || !nonCheckCodeCardId.matches("\\d+")) {
            // 如果传的不是数据返回N
            return 'N';
        }
        char[] chs = nonCheckCodeCardId.trim().toCharArray();
        int luhmSum = 0;
        for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if (j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
    }

    public static String toMD5(String source) {
        if (null == source || "".equals(source)) {
            return null;
        }
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(source.getBytes());
            return toHex(digest.digest());
        } catch (NoSuchAlgorithmException ignored) {
        }
        return null;
    }


    /**
     * 判断是否是null或长度为0
     *
     * @param str 要判断字符串
     * @return 空：true
     */
    public static boolean isNullOrEmpty(String str) {
        try {
            if (str == null) {
                return true;
            }
            if (str.length() == 0) {
                return true;
            }
            if (str.isEmpty()) {
                return true;
            }
            if (str.replace(" ", "").toLowerCase().equalsIgnoreCase("null")) {
                return true;
            }
            if ("".equals(str.replace(" ", ""))) {
                return true;
            }
        } catch (Exception e) {
            return true;
        }
        return false;
    }


    /**
     * will trim the string
     *
     * @param s
     * @return
     */
    public static boolean isEmpty(String s) {
        if (null == s) {
            return true;
        }
        if (s.length() == 0) {
            return true;
        }
        if (s.trim().length() == 0) {
            return true;
        }
        return false;
    }

    /**
     * 获取当前的时间戳
     * 毫秒
     *
     * @return
     */
    public static String getTimeStameMilli() {
        //获取当前的毫秒值
        long time = System.currentTimeMillis();
        //将毫秒值转换为String类型数据
        String time_stamp = String.valueOf(time);
        //返回出去
        return time_stamp;

    }

    /**
     * 调此方法输入所要转换的时间输入例如（"2014-06-14-16-09-00"）返回时间戳
     *
     * @param time
     * @return
     */
    public static String dataOne(String time) {
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                Locale.CHINA);
        Date date;
        String times = null;
        try {
            date = sdr.parse(time);
            long l = date.getTime();
            String stf = String.valueOf(l);
            times = stf.substring(0, 13);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return times;
    }

    /**
     * 将时间戳转换为时间
     * <p>
     * s就是时间戳 2020-06-10 06:32:10
     */

    public static String stampToDate(String s) {
        if (s.length() == 10) {
            s = s + "000";
        }
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //如果它本来就是long类型的,则不用写这一步
        long lt = new Long(s);
//        Date date = new Date(lt * 1000);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    public static String ShiFenDate(String s) {
        if (s.length() == 10) {
            s = s + "000";
        }
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        //如果它本来就是long类型的,则不用写这一步
        long lt = new Long(s);
//        Date date = new Date(lt * 1000);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    public static String YueRiDate(String s) {
        if (s.length() == 10) {
            s = s + "000";
        }
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd");
        //如果它本来就是long类型的,则不用写这一步
        long lt = new Long(s);
//        Date date = new Date(lt * 1000);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    public static String YueRiShiFenDate(String s) {
        if (s.length() == 10) {
            s = s + "000";
        }
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd  HH:mm");
        //如果它本来就是long类型的,则不用写这一步
        long lt = new Long(s);
//        Date date = new Date(lt * 1000);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    public static Calendar strToCalendar(String tim) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse(tim);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar;
    }

    /**
     * 获取当前时间
     */
    public static String currentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        return sdf.format(date);
    }

    /**
     * 获取时间
     */
    public static String getTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        Date date = new Date();
        return sdf.format(date);
    }

    /**
     * 获取时间
     *
     * @param timetype MM-dd hh:mm
     * @return
     */
    public static String getTime(String timetype) {
        SimpleDateFormat sdf = new SimpleDateFormat(timetype);
        Date date = new Date();
        return sdf.format(date);
    }


    public static String getTimeSpanFormat(long time) {
        String date = null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm");
        date = df.format(new Date(time));
        return date;
    }

    public static String getTimeSpanFormat(String time) {
        long lon = Long.parseLong(time);
        String date = null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm");
        date = df.format(new Date(lon));
        return date;
    }

    public static String getTimeFormat(String time) {
        long lon = Long.parseLong(time);
        String date = null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd");
        date = df.format(new Date(lon));
        return date;
    }
    public static String getTimeNYSFFormat(String time) {
        long lon = Long.parseLong(time);
        String date = null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        date = df.format(new Date(lon));
        return date;
    }
    public static String getTimeAllFormat(String time) {
        long lon = Long.parseLong(time);
        String date = null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        date = df.format(new Date(lon));
        return date;
    }

    public static Date getTimeDateFormat(String time) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = df.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static String MSStampHHmmStr(long time) {
        String date = null;
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");
        Long aLong = Long.valueOf(time);
        date = df.format(aLong);
        return date;
    }

    /**
     * 将时间戳转换为时间
     * <p>
     * s就是时间戳
     */

    public static String stampSqlToDate(String s) {
        if (s.length() == 10) {
            s = s + "000";
        }
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ");
        //如果它本来就是long类型的,则不用写这一步
        long lt = new Long(s);
//        Date date = new Date(lt * 1000);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    public static String toHex(byte[] buf) {
        if (buf == null) {
            return "";
        }
        StringBuffer result = new StringBuffer(2 * buf.length);
        for (byte aBuf : buf) {
            appendHex(result, aBuf);
        }
        return result.toString();
    }

    private static void appendHex(StringBuffer sb, byte b) {
        sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
    }


    public static boolean isUrl(String str) {
        return url_pattern.matcher(str).matches();
    }

    //手机正则
    public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
        if (str == null) {
            return false;
        }
        if (str.length() != 11) {
            return false;
        }
        String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 验证码正则 默认6位
     */
    public static boolean isCodes(String codes) {
        Pattern p = Pattern.compile("\\d{6}$");
        Matcher m = p.matcher(codes);
        return m.matches();
    }

    /**
     * 验证码正则 验证码长度
     */
    public static boolean isCodes(String codes, int length) {
        Pattern p = Pattern.compile(String.format("\\d{%d}$", length));
        Matcher m = p.matcher(codes);
        return m.matches();
    }


    /***
     *
     * @param input : 银行卡号,例如"6225880137706868"
     * @return
     */
    public static String formBankCard(String input) {
        return input.replaceAll("([\\d]{4})(?=\\d)", "$1 ");
    }

    /**
     * 区间随机数
     *
     * @param min 区间最小值
     * @param max 区间最大值
     * @return 区间正随机数
     */
    public static int intRandom(int min, int max) {
//        Random random = new Random();
//        return random.nextInt(max) % (max - min + 1) + min;

        if (min > max) {
            return 0;
        }
        if (min == max) {
            return min;
        }
        return new Random().nextInt(max - min + 1) + min;
    }

    /**
     * @param min
     * @param max
     * @return 未完成
     */
    public static String douRandom(int min, int max) {

        if (min > max) {
            return "0";
        }
        if (min == max) {
            return String.valueOf(min);
        }
        double money = (new Random().nextDouble() * (20 - 1) + 1);
        DecimalFormat df = new DecimalFormat("#.00");
        return df.format(money);
    }

    /*
     * 将时间转换为时间戳
     */
    public static String dateToStamp(String time) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = simpleDateFormat.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long ts = date.getTime();
        return String.valueOf(ts);
    }

    /**
     * 获取指定字符串出现的次数
     * 返回在此字符串中第一次出现指定字符处的索引，从指定的索引开始搜索
     *
     * @param srcText  源字符串
     * @param findText 要查找的字符串
     * @return
     */
    public static int getRepeatCount(String srcText, String findText) {
        int count = 0;
        int index = 0;
        while ((index = srcText.indexOf(findText, index)) != -1) {
            index = index + findText.length();
            count++;
        }
        return count;

    }

    /**
     * 查询复制中的字符串 是否有某段 字符串
     *
     * @param soap
     * @param rgex
     * @return
     */
    public static String getSubUtilSimple(String soap, String rgex) {

        Pattern pattern = Pattern.compile(rgex);// 匹配的模式

        Matcher m = pattern.matcher(soap);

        while (m.find()) {

            return m.group(1);

        }

        return "";

    }

    public static String convertListToXString(List<String> strlist) {
        StringBuffer sb = new StringBuffer();
        if (strlist.size() > 0) {
            for (int i = 0; i < strlist.size(); i++) {
                if (i == 0) {
                    sb.append(strlist.get(i));
                } else {
                    sb.append("/").append(strlist.get(i));
                }
            }
        }
        return sb.toString();
    }

    /**
     * lsit转字符串。带逗号 1,2,3,4,
     *
     * @param strlist
     * @return
     */
    public static String convertListToString(List<String> strlist) {
        StringBuffer sb = new StringBuffer();
        if (strlist.size() > 0) {
            for (int i = 0; i < strlist.size(); i++) {
                if (i == 0) {
                    sb.append(strlist.get(i));
                } else {
                    sb.append(",").append(strlist.get(i));
                }
            }
        }
        return sb.toString();
    }

    public static String convertListToStringInt(List<Integer> strlist) {
        StringBuffer sb = new StringBuffer();
        if (strlist.size() > 0) {
            for (int i = 0; i < strlist.size(); i++) {
                if (i == 0) {
                    sb.append(strlist.get(i));
                } else {
                    sb.append(",").append(strlist.get(i));
                }
            }
        }
        return sb.toString();
    }

    /**
     * lsit转字符串。带逗号 1234
     *
     * @param strlist
     * @return
     */
    public static String convertListToStr(List<String> strlist) {
        StringBuffer sb = new StringBuffer();
        if (strlist.size() > 0) {
            for (int i = 0; i < strlist.size(); i++) {
                if (i == 0) {
                    sb.append(strlist.get(i));
                } else {
                    sb.append(strlist.get(i));
                }
            }
        }
        return sb.toString();
    }


}
